#!/bin/bash

set -e

# config params
# Target directory
TARGET_DIR=$(dirname "$(pwd)")
# RootFS directory:Compile environment
ROOTFS_DIR="${TARGET_DIR}/sys_rootfs"
# CPU architecture：ARCH="amd64"、ARCH="arm64"
ARCH="amd64"
# Debian kernel version
KERNEL_VERSION="6.1.0-35-${ARCH}"
# builder sys work dir
WORK_DIR=$(cd "$(dirname "$0")" && pwd -P)
echo "builder sys work dir: ${WORK_DIR}"

echo "Generate initramfs..."
# initramfs dir
INITRAMFS_DIR="${WORK_DIR}/initramfs/${ARCH}"
# Build a custom initramfs for Debian initramfs
if [ -d ${INITRAMFS_DIR} ]; then
    echo "Remove old initramfs dir..."
    rm -rf ${INITRAMFS_DIR}
fi
mkdir -p ${INITRAMFS_DIR} && cd ${INITRAMFS_DIR}
#file ${WORK_DIR}/initrd/initrd.img-${KERNEL_VERSION}
# zstd initrd
zstd -dc ${WORK_DIR}/initrd/initrd.img-${KERNEL_VERSION} | cpio -idm -D ${INITRAMFS_DIR}

# partition and format tools
echo "Add partition command..."
# partition cmd:parted、mkfs.ext2、mkfs.ext3、mkfs.ext4
# dir:/usr/sbin cmd 
cp ${ROOTFS_DIR}/usr/sbin/parted ${INITRAMFS_DIR}/usr/sbin
cp ${ROOTFS_DIR}/usr/sbin/mkfs.ext2 ${INITRAMFS_DIR}/usr/sbin
cp ${ROOTFS_DIR}/usr/sbin/mkfs.ext3 ${INITRAMFS_DIR}/usr/sbin
cp ${ROOTFS_DIR}/usr/sbin/mkfs.ext4 ${INITRAMFS_DIR}/usr/sbin
# dir:/usr/bin cmd
cp ${ROOTFS_DIR}/usr/bin/lsblk ${INITRAMFS_DIR}/usr/bin

# copy kernel libraries
cp ${ROOTFS_DIR}/usr/lib/x86_64-linux-gnu/libparted.so.2.0.4 ${INITRAMFS_DIR}/usr/lib/x86_64-linux-gnu
cp ${ROOTFS_DIR}/usr/lib/x86_64-linux-gnu/libmount.so.1.1.0 ${INITRAMFS_DIR}/usr/lib/x86_64-linux-gnu
cp ${ROOTFS_DIR}/usr/lib/x86_64-linux-gnu/libsmartcols.so.1.1.0 ${INITRAMFS_DIR}/usr/lib/x86_64-linux-gnu
cp ${ROOTFS_DIR}/usr/lib/x86_64-linux-gnu/libreadline.so.8.2 ${INITRAMFS_DIR}/usr/lib/x86_64-linux-gnu
cp ${ROOTFS_DIR}/usr/lib/x86_64-linux-gnu/libtinfo.so.6.4 ${INITRAMFS_DIR}/usr/lib/x86_64-linux-gnu
cp ${ROOTFS_DIR}/usr/lib/x86_64-linux-gnu/libuuid.so.1.3.0 ${INITRAMFS_DIR}/usr/lib/x86_64-linux-gnu
cp ${ROOTFS_DIR}/usr/lib/x86_64-linux-gnu/libext2fs.so.2.4 ${INITRAMFS_DIR}/usr/lib/x86_64-linux-gnu
cp ${ROOTFS_DIR}/usr/lib/x86_64-linux-gnu/libe2p.so.2.3 ${INITRAMFS_DIR}/usr/lib/x86_64-linux-gnu
cp ${ROOTFS_DIR}/usr/lib/x86_64-linux-gnu/libcom_err.so.2.1 ${INITRAMFS_DIR}/usr/lib/x86_64-linux-gnu

# cd kernel dir
cd ${INITRAMFS_DIR}/usr/lib/x86_64-linux-gnu
# create symlinks
ln -s libparted.so.2.0.4 libparted.so.2
ln -s libmount.so.1.1.0 libmount.so.1
ln -s libsmartcols.so.1.1.0 libsmartcols.so.1
ln -s libreadline.so.8.2 libreadline.so.8
ln -s libtinfo.so.6.4 libtinfo.so.6
ln -s libuuid.so.1.3.0 libuuid.so.1
ln -s libext2fs.so.2.4 libext2fs.so.2
ln -s libe2p.so.2.3 libe2p.so.2
ln -s libcom_err.so.2.1 libcom_err.so.2

echo "Finish build product initramfs..."
